<?php

namespace app\models\manage;

use think\facade\Validate;
use think\Model;
use think\facade\Session;

class AuthModel extends Model
{
    protected $table = 'manage_account';

    const LEVEL_TYPE_ADMIN = 1;
    const LEVEL_TYPE_NORMAL = 0;

    private $levelTypeList = [
        self::LEVEL_TYPE_ADMIN => '超管',
        self::LEVEL_TYPE_NORMAL => '普通用户',
    ];


    public function loginIn(array $params = [])
    {
        $rule = [
            'username' => 'require|alphaNum|max:16',
            'password' => "require|max:16",
        ];

        $message = [
            'username.require' => '用户名不能为空',
            'username.alphaNum' => '用户名只能字母与数字',
            'username.16' => '用户名最多16个字符',
            'password.require' => '密码不能为空',
            'password.max' => '密码最多16个字符',
        ];
        $validate = Validate::message($message)->rule($rule);
        if (!$validate->check($params)) {
            return funReturn(STATUS_CODE_DATAERROR, $validate->getError());
        }
        $info = $this->getAccountInfoByUsername($params['username']);

        if (!$info) {
            return funReturn(STATUS_CODE_NOTFOUND, '账号或密码错误');
        }

        if (encryptPassword($params['password'], $info['salt']) != $info['password']) {
            return funReturn(STATUS_CODE_DATAERROR, '账号或密码错误');
        }
        Session::set('manage_admin', [
            'account_id' => $info['id'],
            'username' => $info['username'],
            'nickname' => $info['nickname'],
            'role_id' => $info['role_id'],
            'avart_url' => $info['avart_url'],
        ]);
        $this->setAccountLoginIn($info['id'], $params['client_ip'] ?? '');
        return funReturn(STATUS_CODE_SUCCESS, 'success');

    }


    /**
     * Note:通过用户名获取账号详情
     * User:端木凌风
     * Date:2022-11-24 16:52
     * @param $username
     * @param $where
     * @return void
     */
    public function getAccountInfoByUsername($username, array $where = [])
    {
        $where['username'] = $username;
        return $this->getAccountInfoByUk($where);
    }


    /**
     * Note:通过id获取账号详情
     * User:端木凌风
     * Date:2022-04-12 13:50
     * @param $id
     * @return array
     */
    public function getAccountInfoById($id, array $where = [])
    {
        $where['id'] = $id;
        return $this->getAccountInfoByUk($where);

    }


    /**
     * Note:通过唯一键获取详情
     * User:端木凌风
     * Date:2022-11-24 16:41
     * @param array $params
     * @return void
     */
    public function getAccountInfoByUk(array $params = [])
    {
        $isAllow = false;
        $where = [
            ['is_delete', '=', 0]
        ];
        if (isset($params['id']) && intval($params['id']) > 0) {
            $where[] = ['id', '=', $params['id']];
            $isAllow = true;
        }
        if (isset($params['username']) && (string)$params['username'] != '') {
            $where[] = ['username', '=', $params['username']];
            $isAllow = true;
        }
        if (!$isAllow) return [];
        $info = self::table($this->table)->where($where)->find();
        $info = $info ? $info->toArray() : [];
        if ($info) {
            $info['level_name'] = $this->levelTypeList[$info['level']] ?? '';
            $info['avart_url'] = $info['avart']; //预留 数据库不存真实地址，此处转换出真实地址
        }
        return $info;

    }

    public function setAccountLoginIn($accountId, $clientIP = '')
    {
        self::where("id", $accountId)->update([
            'last_login_time' => date('Y-m-d H:i:s'),
            'last_login_ip' => $clientIP
        ]);
    }

    /**
     * Note:退出登录
     * User:端木凌风
     * Date:2022-04-12 13:49
     * @return array
     */
    public function loginOut()
    {
        Session::delete('manage_admin');
        return funReturn(STATUS_CODE_SUCCESS, 'success');
    }

    /**
     * 修改密码
     * @param $accountId
     * @param $password
     * @param $passwordConfirm
     * @param $originPassword
     * @return array
     */
    public function editPassword($accountId, $password, $passwordConfirm, $originPassword)
    {
        if (empty($password)) return funReturn(STATUS_CODE_DATAERROR, '请输入新密码');
        if ($password != $passwordConfirm) return funReturn(STATUS_CODE_DATAERROR, '两次输入的密码不一致');
        $info = $this->getAccountInfoById($accountId);
        if (!$info) {
            return funReturn(STATUS_CODE_DATAERROR, '数据不存在');
        }

        $salt = $info['salt'];
        $oldPassword = $info['password'];
        if (encryptPassword($originPassword, $salt) != $oldPassword) {
            return funReturn(STATUS_CODE_DATAERROR, '原密码错误');
        }

        $newSalt = createSalt();
        $password = encryptPassword($password, $newSalt);
        $res = self::where('id', $accountId)->update(['password' => $password, 'salt' => $newSalt]);
        if ($res === false) {
            return funReturn(STATUS_CODE_INSIDEERROR, '操作失败请重试');
        }
        return funReturn(STATUS_CODE_SUCCESS, '操作成功');
    }

}